 import * as echarts from '../../ec-canvas/echarts';

const app = getApp();


var nightValue=[]
var noonValue = []
var morningValue = []
var viewMorning = []
var viewNoon = []
var viewNight = []


var tipViewMorning=""
var tipViewNoon = ""
var tipViewNight = ""
var standerdLength = [100, 100, 100, 100, 100,]
var standerdValues = []





var cost1 = [10, 30, 60, 70, 100,]//本期比上期（大于1按1处理）

var dataCost = [100, 55, 200, 1000.01, 200000, 200, 200000]//真是的金额
var totalCost = ['100毫克', 100, 100, 100, 100]//比例综合
var totalCost1 = [100, 100, 100, 100, 100]


var visits = [100, 100, 100, 100, 100, 100, 100]
var visits1 = [100, 100, 100, 100, 100, 100, 100]//本期占总的百分比*100
var grade = ['钙', '钙', '钙钙脂肪', '2级隐患', '1级隐患',]
var myColor = ['#38B0DE', '#38B0DE', '#38B0DE', '#38B0DE', '#38B0DE',]
var myColor1 = ['#21BF57', '#21BF57', '#56D0E3', '#56D0E3', '#F57474',]
var data = {
  grade: grade,
  cost1:cost1,
  totalCost: totalCost,
  visits: visits,
  dataCost: dataCost
};

function initChartmorning(canvas, width, height, dpr) {//早开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

   // backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '标准摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        interval: 0,
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [ {
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
         // barBorderRadius: 16,
          color: function (params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
         formatter: function (data) {
          let unit="克"
           if (data.dataIndex==0){
             unit = "千卡"
           }
           if (data.dataIndex == 4) {
             unit = "毫克"
           }
           return standerdValues[data.dataIndex] + unit
         },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: standerdLength,
    }]
  };
  chart.setOption(option);
  return chart;
}
function initChartmorning1(canvas, width, height, dpr) {//早开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

  //  backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '实际摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
    },
    yAxis: [{

      show:false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          color: function (params) {
            let percentage=morningValue[params.dataIndex]
            let color ="#56D0E3"
            if (percentage<50){
              color = "#21BF57"
            }
            if (percentage >=100){
              color = "#F57474"
            }
            return color
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return viewMorning[data.dataIndex] 
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: morningValue,
    }]
  };
  chart.setOption(option);
  return chart;
}

function initChartnoon(canvas, width, height, dpr) {//中开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

   // backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '标准摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [ {
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            let unit = "克"
            if (data.dataIndex == 0) {
              unit = "千卡"
            }
            if (data.dataIndex == 4) {
              unit = "毫克"
            }
            return standerdValues[data.dataIndex] + unit
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: standerdLength,
    }]
  };
  chart.setOption(option);
  return chart;
}
function initChartnoon1(canvas, width, height, dpr) {//中开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

   // backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '实际摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [ {
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            let percentage = noonValue[params.dataIndex]
            let color = "#56D0E3"
            if (percentage < 50) {
              color = "#21BF57"
            }
            if (percentage >= 100) {
              color = "#F57474"
            }
            return color
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return viewNoon[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: noonValue,
    }]
  };
  chart.setOption(option);
  return chart;
}



function initChartnight(canvas, width, height, dpr) {//晚开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

  // backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '标准摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [{
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            var num = myColor.length;
            return myColor[params.dataIndex % num]
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            let unit = "克"
            if (data.dataIndex == 0) {
              unit = "千卡"
            }
            if (data.dataIndex == 4) {
              unit = "毫克"
            }
            return standerdValues[data.dataIndex] + unit
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: standerdLength,
    }]
  };
  chart.setOption(option);
  return chart;
}
function initChartnight1(canvas, width, height, dpr) {//晚开始
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {

   // backgroundColor: '#05274C',
    title: {
      top: '2%',
      left: 'center',
      text: '实际摄入',
      textStyle: {
        align: 'center',
        color: '#000000',
        fontSize: 18
      }
    },
    grid: {
      left: '60',
      right: '30'
    },
    xAxis: {
      type: 'category',

      data: ['能量', '蛋白质', '脂肪', '碳水化物', '钙'],
      axisLabel: {
        margin: 20,
        color: '#000000',
        textStyle: {
          fontSize: 10
        },
      },
      axisLine: {
        lineStyle: {
          color: '#d2d2d2',
        }
      },
      axisTick: {
        show: false
      },
      // data: data.grade
    },
    yAxis: [{

      show: false
    }],

    series: [ {
      type: 'bar',
      barGap: '-85%',
      barWidth: '30%',
      itemStyle: {
        normal: {
          // barBorderRadius: 16,
          color: function (params) {
            let percentage = nightValue[params.dataIndex]
            let color = "#56D0E3"
            if (percentage < 50) {
              color = "#21BF57"
            }
            if (percentage >= 100) {
              color = "#F57474"
            }
            return color
          },
        }
      },
      max: 1,
      label: {
        normal: {
          show: true,
          position: 'top',
          formatter: function (data) {
            return viewNight[data.dataIndex]
          },
        }
      },
      labelLine: {
        show: true,
      },
      z: 2,
      data: nightValue,
    }]
  };
  chart.setOption(option);
  return chart;
}


Page({
  onShareAppMessage: function (res) {
    return {
      title: '智慧餐厅',
      path: '/pages/index/index',
      success: function () { },
      fail: function () { }
    }
  },
  
  data: {
    // ec: {
    //   onInit: initChart,
    //    winWidth: 0,
    //   winHeight: 0,
      
      
    // },
    standardIntake:null,
    currentTab:0,
    imagePath: app.globalData.imagePath,
    night:null,
    noon: null,
    morning: null
  },
  bindViewTap: function () {
    wx.navigateTo({
      url: '../home/home'
    })
  },
  index:function(){
    wx.navigateTo({
      url: '../index/index'
    })
  },
  
  ls: function () {
    wx.navigateTo({
      url: '../history/history',
    })
  },
  onLoad: function () {
    this.echartsComponnet = this.selectComponent('#mychart-dom-graph');
   
    var that = this;

    /**
     * 获取当前设备的宽高
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }

    });
  },

  onShow:function(){
    console.log("初始化餐厅页")
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {

        } else {
          // 用户没有授权
          that.setData({
            isHide: true
          });
          return
        }
      }
    });
    app.initUserInfo()
    this.getData(); //获取数据
  },
  getData: function () {
    let standardIntake = app.globalData.userInfo.standardIntake
    standerdValues=[]
    standerdValues.push(Math.round(standardIntake.energyCal / 3))
    standerdValues.push(Math.round(standardIntake.protein / 3))
    standerdValues.push(Math.round(standardIntake.fatAvg / 3))
    standerdValues.push(Math.round(standardIntake.carbohyMinGd / 3))
    standerdValues.push(Math.round(standardIntake.elementCa / 3))
    var that = this;
  	/**
  	 * 此处的操作：
  	 * 获取数据json
  	 */
    wx.request({
      url: app.globalData.serverPath +"/meal/getTodayMealByUserId?userId=" + app.globalData.userInfo.userId,
   
      method: 'get',
      header: { 'content-type': 'application/json' },
      success: (res) => {
        console.log("早中晚",res.data.result)
      
        let currentTab=0
        let intake = res.data.result[0];//早
        if (intake != null) {
          // morningValue = [intake.calcium, intake.fats, intake.carbohydrates, intake.proteins, intake.energy]
          morningValue=that.getPercentage(intake, standardIntake)
          tipViewMorning = "钙:" + intake.calcium + "毫克\n脂肪" + intake.fats + "克\n碳水化合物" + intake.carbohydrates + "克\n蛋白质" + intake.proteins + "克\n能量" + intake.energy + "千卡";
          viewMorning=[]
          viewMorning.push(intake.energy+"千卡")
          viewMorning.push(intake.proteins + "克")
          viewMorning.push(intake.fats + "克")
          viewMorning.push(intake.carbohydrates + "克")
          viewMorning.push(intake.calcium + "毫克")
        }

        intake = res.data.result[1];//中
        if (intake != null) {
          currentTab=1
          noonValue = that.getPercentage(intake, standardIntake)
         // noonValue = [intake.calcium, intake.fats, intake.carbohydrates, intake.proteins, intake.energy]
          tipViewNoon = "钙:" + intake.calcium + "毫克\n脂肪" + intake.fats + "克\n碳水化合物" + intake.carbohydrates + "克\n蛋白质" + intake.proteins + "克\n能量" + intake.energy + "千卡";

          viewNoon = []
          viewNoon.push(intake.energy + "千卡")
          viewNoon.push(intake.proteins + "克")
          viewNoon.push(intake.fats + "克")
          viewNoon.push(intake.carbohydrates + "克")
          viewNoon.push(intake.calcium + "毫克")

        }
        intake=res.data.result[2];//晚
        if (intake != null) {
          currentTab = 2
          //nightValue = [intake.calcium, intake.fats, intake.carbohydrates, intake.proteins, intake.energy]
          nightValue = that.getPercentage(intake, standardIntake)
          tipViewNight = "钙:" + intake.calcium + "毫克\n脂肪" + intake.fats + "克\n碳水化合物" + intake.carbohydrates + "克\n蛋白质" + intake.proteins + "克\n能量" + intake.energy + "千卡";

          viewNight = []
          viewNight.push(intake.energy + "千卡")
          viewNight.push(intake.proteins + "克")
          viewNight.push(intake.fats + "克")
          viewNight.push(intake.carbohydrates + "克")
          viewNight.push(intake.calcium + "毫克")
        }
        

        that.setData({
          ecnight: {
            onInit: initChartnight,
            winWidth: 0,
            winHeight: 0,
          },
          ecnight1: {
            onInit: initChartnight1,
            winWidth: 0,
            winHeight: 0,
          },
          ecnoon: {
            onInit: initChartnoon,
            winWidth: 0,
            winHeight: 0,
          },
          ecnoon1: {
            onInit: initChartnoon1,
            winWidth: 0,
            winHeight: 0,
          },
          ecmorning: {
            onInit: initChartmorning,
            winWidth: 0,
            winHeight: 0,
          },
          ecmorning1: {
            onInit: initChartmorning1,
            winWidth: 0,
            winHeight: 0,
          },


          night: res.data.result[2],
          noon: res.data.result[1],
          morning: res.data.result[0],
          currentTab: currentTab
        })
     
      }
    });
  },

  getPercentage: function (intake, standardIntake) {
    let percenttageIntake=[]
    percenttageIntake.push(Math.round(intake.energy / (standardIntake.energyCal / 3) * 100))
    percenttageIntake.push(Math.round(intake.proteins / (standardIntake.protein / 3) * 100))
    percenttageIntake.push(Math.round(intake.fats / (standardIntake.fatAvg/3)*100))
    percenttageIntake.push(Math.round(intake.carbohydrates / (standardIntake.carbohyMinGd / 3) * 100))
    percenttageIntake.push(Math.round(intake.calcium / (standardIntake.elementCa / 3) * 100))
   
    for (let i in  percenttageIntake){
      if (percenttageIntake[i]>100){
        percenttageIntake[i]=100
      }
    }
    console.log("百分比值",percenttageIntake)
   // [intake.calcium, intake.fats, intake.carbohydrates, intake.proteins, intake.energy]

    return percenttageIntake
  },
  //  tab切换逻辑
  swichNav: function (e) {

    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  bindChange: function (e) {

    var that = this;
    that.setData({ currentTab: e.detail.current });

  },

  onReady() {
  },
  yy: function () {
    wx.navigateTo({
      url: '../voice/index',
    })
  },
});
